<template>
  <div>
    <div class="list-table">
      <div class="area-header">
        <span class="area-header-title">{{ $t('项目合同') }}</span>
      </div>
      <el-form ref="queryForm" :model="queryParams" :inline="true">
        <el-form-item :label="$t('申请标题')" prop="actTitle">
          <el-input v-model="queryParams.actTitle" :placeholder="$t('申请标题')" @keyup.enter.native="queryHandle" />
        </el-form-item>
        <el-form-item :label="$t('申请人')" prop="applyUserId">
          <UserSelect
            v-model="queryParams.applyUserId"
            :placeholder="$t('申请人')"
          />
        </el-form-item>
        <el-form-item :label="$t('合同名称')" prop="name">
          <el-input
            v-model="queryParams.name"
            :placeholder="$t('合同名称')"
            clearable
            @keyup.enter.native="queryHandle"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['deal:contract:edit']"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="addHandle"
          >{{ $t("新增") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-hasPermi="['deal:contract:export']" type="warning" icon="el-icon-download" size="mini" @click="exportHandle">{{ $t("导出") }}</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" tooltip-effect="darkTable" :data="dealContractList" :show-summary="true" :summary-method="getSummaries" class="nowrapTable showOnlyLine" border>
        <el-table-column type="index" align="center" show-overflow-tooltip width="55">
          <template slot-scope="scope">
            <el-radio v-model="radioView" :label="(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1" @click.native.prevent="choiceRadio(scope.$index, scope.row)">
              <span style="display: none;" />
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
          <template slot-scope="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('申请标题')" align="center" prop="actTitle" min-width="250px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="link-type" @click="updateHandle(scope.row)">{{ scope.row.actTitle }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="isShowDeal === 'hidden'" :label="$t('项目名称')" show-overflow-tooltip align="center" prop="dealName" min-width="200px" />
        <el-table-column :label="$t('合同名称')" align="center" prop="name" show-overflow-tooltip min-width="200px" />
        <el-table-column :label="$t('合同金额') + $t('金额单位')" header-align="center" align="right" prop="money" show-overflow-tooltip min-width="100px">
          <template slot-scope="scope">
            <span class="money-text">{{ moneyFormat(scope.row.money, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('币种')" align="center" prop="currency" :formatter="currencyFormat" />
        <el-table-column :label="$t('申请人')" align="center" prop="userName" show-overflow-tooltip min-width="110" />
        <el-table-column :label="$t('申请时间')" align="center" prop="applyTime" show-overflow-tooltip min-width="110">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.applyTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('审批状态')" align="center" min-width="110">
          <template slot-scope="scope">
            <ProcessStatus :status="scope.row.actStatus" :act-id="scope.row.actId" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('操作')" align="center" class-name="small-padding fixed-width" min-width="200">
          <template slot-scope="scope">
            <div style="display: flex;align-items: center;justify-content: center;">
              <!-- 启动流程，终止流程，修改，删除 四个按钮 -->
              <ListBtn :bus-data="scope.row" has-permi="deal:contract" :other-btn="!(scope.row.actStatus === 'W' || scope.row.lastHistoricalId)" data-table="deal_contract_spo" />
              <el-button
                v-if="scope.row.actStatus === 'W'"
                v-hasPermi="['deal:contract:edit']"
                size="small"
                type="text"
                icon="el-icon-brush"
                @click="contractChanges(scope.row)"
              >{{ $t('合同变更') }}</el-button>
              <el-button
                v-if="scope.row.lastHistoricalId"
                v-hasPermi="['deal:contract:view']"
                size="small"
                type="text"
                icon="el-icon-view"
                style="margin-left: 10px;"
                @click="historicalContractView(scope.row)"
              >{{ $t('合同历史') }}</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改合同信息对话框 -->
      <el-dialog :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
        <dealContractSpoForm ref="dealContractSpoForm" />
      </el-dialog>

      <!-- 历史合同 -->
      <el-dialog :title="$t(title)" :visible.sync="historicalContractOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
        <historicalContractSpoList ref="historicalContractSpoList" />
      </el-dialog>
    </div>

    <!-- 关键条款 -->
    <div style="height: 20px" />
    <dealTermsList ref="dealTermsList" has-permi="financing:contract" />
  </div>
</template>

<script>
import {
  listDealContractSpo,
  delDealContractSpo,
  terminationChange,
  getDealContractSpoSum
} from '@/api/deal/spo/dealContractSpo.js'
import ProcessStatus from '@/components/Act/ProcessStatus'
import dealContractSpoForm from './dealContractSpoForm.vue'
import historicalContractSpoList from '@/views/deal/spo/contract/historicalContractSpoList.vue'
import dealTermsList from '@/views/deal/terms/dealTermsList.vue'
export default {
    components: {
      dealTermsList,
        dealContractSpoForm,
        ProcessStatus,
        historicalContractSpoList
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 总条数
          total: 0,
          // 合同信息表格数据
          dealContractList: [],
          dealContractSum: {},
          // 弹出层标题
          title: '项目合同',
          radioView: '',
          // 是否显示弹出层
          formOpen: false,
          // 历史合同弹出层
          historicalContractOpen: false,
          // 查询参数
          queryParams: {
              applyUserId: '',
              dealId: this.$route.query.id,
              name: undefined,
              company: undefined,
              pageNum: 1,
              pageSize: 10
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {
          },
          // 更新付款时间
          // 遮盖层
          dialogVisiblePayTime: false,
          // 选中的时间
          dialogVisiblePayTimeValue: '',
          // 要修改的ID
          dialogVisiblePayTimeId: '',
          isShowDeal: undefined,
          currencyOptions: []
      }
  },
  created() {
      this.getList()
      this.$bus.$emit('async_done')
      this.getDicts('currency').then(response => {
        this.currencyOptions = response.data
      })
  },
  methods: {
    /** 查询合同信息列表 */
    getList() {
      this.loading = true
      if (this.$route.query.id === undefined || this.$route.query.id === null || this.$route.query.id === '') {
        this.isShowDeal = 'hidden'
      }
      listDealContractSpo(this.queryParams).then(response => {
        this.dealContractList = response.rows
        this.total = response.total

        getDealContractSpoSum(this.queryParams).then(res => {
          this.dealContractSum = res.data
        })

        // 字段校正字典label
        this.getDicts('sys_yes_no').then(dictYesNo => {
          dictYesNo.data.forEach((item) => {
            this.dealContractList.forEach(dict => {
              if (item.dictValue === dict.isSeal) {
                dict.isSeal = item.dictLabel
              }
            })
          })
        })

        this.getDicts('payment_no_deal').then(dictCPN => {
          dictCPN.data.forEach((item) => {
            this.dealContractList.forEach(dict => {
              if (item.dictValue === dict.isPayment) {
                dict.isPayment = item.dictLabel
              }
            })
          })
        })
        this.loading = false
        this.$refs.dealTermsList.getList()
      })
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            applyUserId: undefined,
            dealId: this.$route.query.id,
            dealName: undefined,
            applyTime: undefined,
            name: undefined,
            money: undefined,
            typeOne: undefined,
            typeTwo: undefined,
            company: undefined,
            projectOrFund: undefined,
            isPayment: undefined,
            isSeal: undefined,
            useSealOne: undefined,
            useSealTwo: undefined,
            payCompletionTime: undefined,
            lastHistoricalId: undefined,
            abstracts: undefined,
            createBy: undefined,
            updateBy: undefined,
            createTime: undefined,
            updateTime: undefined,
            delFlag: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.title = '项目合同'
        this.$nextTick(() => {
          this.$refs.dealContractSpoForm.otherBtnHide = false
          this.$refs.dealContractSpoForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.dealContractSpoForm.init(row)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return delDealContractSpo(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        this.downLoadExcel('/contract/dealContractSpo/export', this.queryParams)
    },
    // 投资币种字典翻译
    currencyFormat(row) {
      return this.selectDictLabel(this.currencyOptions, row.currency)
    },
    /** 合同变更 */
    contractChanges(row) {
      this.formOpen = true
      if (row.id !== '' && row.id !== null && row.id !== undefined) {
        this.$nextTick(() => {
          // 调用form页面的 init 方法初始化数据
          this.$refs.dealContractSpoForm.otherBtnHide = false
          this.$refs.dealContractSpoForm.contractChanges(row)
        })
      } else {
        this.msgError('发生错误, 刷新下试试!')
      }
    },
    // 合同历史
    historicalContractView(row) {
      this.title = '历史合同'
      this.historicalContractOpen = true
      this.$nextTick(() => {
        this.$refs.historicalContractSpoList.getList(row)
      })
    },
    // 终止合同变更流程流程执行方法
    stopProcessCurrent(that, actId) {
      console.log(that, actId)
      this.loading = true
      terminationChange(that.busData.id).then(response => {
        console.log(response)
        this.getList()
      })
    },
    // 合计
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 3) {
          sums[index] = this.moneyFormat(this.dealContractSum.money, 'w')
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    choiceRadio(index, row) {
      if (this.radioView === (index + 1)) {
        this.radioView = ''
        this.$nextTick(() => {
          this.$refs.dealTermsList.queryParams.associatedContract = ''
          this.$refs.dealTermsList.queryParams.type = undefined
          this.$refs.dealTermsList.getList()
        })
      } else {
        this.radioView = index + 1
        this.$nextTick(() => {
          this.$refs.dealTermsList.queryParams.associatedContract = row.id
          this.$refs.dealTermsList.queryParams.type = undefined
          this.$refs.dealTermsList.getList()
        })
      }
    }
  }
}
</script>
